<template>
  <div class="ingredient">
    <jc-button
      :btn-arr="['reload', 'sub', 'push', 'option', 'pass', 'batchFill', !list.length && 'check', 'settle']"
      :disab-arr="['close', 'cancel', 'copy', 'com2', 'freeze', 'using']"
      :fbillno="fbillno"
      url="tPrdMo/querycdList"
      @refresh="handleGetUntreated"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @toExcel="handleExport"
      @handleCom1="printing1"
      @pushDown="pushDown"
      @settle="settle"
      @check="check('up')"
      @check1="check('down')"
    />
    <!--    @del="delPublic"-->
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button
          type="primary"
          class="btn"
          size="mini"
          @click="handleQuerySonClass"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <!--      v-el-table-infinite-scroll="load"-->
      <jc-table
        v-loading="loading"
        sortable
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        table-selection
        get-row-keys="fentryId"
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="proUpload"
      >
        <!--单据编号-->
        <template v-slot:btnStates="col">
          <el-link type="primary" @click="proUpload(col.scope.row)">
            {{ col.scope.row.fbillNo }}
          </el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--    产品编码    -->
        <template v-slot:text2Slot="col">
          <el-link type="primary" @click="jumpMateriel1(col.scope.row.faterNumber)">
            {{ col.scope.row.faterNumber }}
          </el-link>
        </template>
        <!--禁用状态-->
        <template v-slot:tagSlot="col">
          <el-tag v-if="col.scope.row.fcloseStatus === 'A'">{{ $t('market.no') }}</el-tag>
          <el-tag v-else type="danger">{{ $t('market.yes') }}</el-tag>
        </template>
        <!--审核状态-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentStatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentStatus }}</el-tag>
        </template>
        <!--齐套-->
        <template v-slot:text3Slot="col">
          <el-tag v-if="col.scope.row.fulls === '不齐料'" type="danger">{{ col.scope.row.fulls }}</el-tag>
          <el-tag v-else>{{ col.scope.row.fulls }}</el-tag>
        </template>
      </jc-table>
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      center
      append-to-body
    >
      <div style="text-align: center;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX" @change="handleOrder">
          <el-radio v-for="item in receipts" :key="item" :label="item">
            {{ item }}
          </el-radio>
        </el-radio-group>
      </div>
      <hr>
      <div v-if="orderBool" style="text-align: center;">
        {{ $t('market.rule') }}
        <el-input v-model="convert" size="mini" disabled style="width: 178px;margin-bottom: 5px;" />
        <br>
        {{ $t('market.billType') }}
        <el-select
          v-model.trim="fbillTypeId"
          size="mini"
          filterable
        >
          <el-option
            v-for="(item, index) in billTypeData"
            :key="index"
            :label="item.fname"
            :value="item.fid"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">
          {{ $t('btn.confirm') }}
        </el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  querycdList,
  auditPrdPpboms,
  unauditPrdPpboms,
  submitPrdPpboms,
  unsubmitPrdPpboms,
  pushToPickmtrl,
  pushToPrdReturnmtrl,
  pushToPrdInstock,
  pushToPrdUninstock,
  finishPrdPpboms,
  pushToSupplement,
  insertProcess, pushMoCheck, insertOutsource
} from '@/api/production/productionList'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina, Forbiders } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'
import { queryViewItem } from '@/api/marketManage/marketOrder'
import { insertMoparts } from '@/api/production/semifinish'

export default {
  name: 'IngredientList',
  components: {
    upDown: () => import('@/components/upDown'),
    search,
    filtration,
    jcButton
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      cha: '',
      fentryData: [],
      ftype: 30,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      isdanjuDialog: false,
      orderLX: this.$t('menu.proPickLian'),
      // '生产领料单''生产退料单''生产入库单''生产退库单' '生产补料单' '生产流程单'
      receipts: [this.$t('menu.proPickLian'), this.$t('menu.proSupplTong'), this.$t('menu.proStirageOrder'),
        this.$t('menu.proTuiStockDetail'), this.$t('menu.supplementary'), this.$t('menu.workFlowOrder'),
        this.$t('menu.qualityOrder'), this.$t('menu.outProcessOrder'), this.$t('menu.semifinishDetail')], // 生产
      fbillTypeId: 184,
      convert: this.$t('market.scylzlc'), // '生产用料单至生产流程单'
      orderBool: false,
      billTypeData: [], // 采购订单单据
      fedBatch: {
        obj: '',
        details: []
      },
      detail: [],
      deleteData: [], // 删除用料单数据
      // 表头
      tableHeight: '60vh',
      tableData: [], // 销售数据
      tableHeader: [
        { label: this.$t('market.billNo'), type: 'states', prop: 'fbillNo', width: '140px' },
        { label: this.$t('market.state'), type: 'state', prop: 'fdocumentStatus', width: '100' },
        { label: this.$t('market.paezText1'), prop: 'fpaezText', width: '110' },
        { label: this.$t('market.proOrderNo'), prop: 'fmobillNo', width: '120' },
        { label: this.$t('market.proOrderSeq'), prop: 'fmoentrySeq', width: '120' },
        { label: this.$t('market.busineState'), prop: 'fstatus' },
        { label: this.$t('market.productNo'), type: 'text2', prop: 'faterNumber', width: '120' },
        { label: this.$t('market.productmodel'), prop: 'fproductmodel', width: '110' },
        { label: this.$t('market.subitemNum'), type: 'order', prop: 'fnumber', width: '130' },
        { label: this.$t('market.subitemName'), prop: 'fname', minWidth: '150' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion', width: '110' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('market.molecule'), prop: 'fnumeraTor', align: 'right', width: '80' },
        { label: this.$t('market.funit'), prop: 'funit', width: '80' },
        { label: this.$t('market.mustqty'), prop: 'fmustQty', align: 'right', width: '80' },
        { label: this.$t('market.pickedQty'), prop: 'fpickedQty', align: 'right', width: '80' },
        { label: this.$t('market.stockQty'), prop: 'fbaseqty', width: '80' },
        { label: this.$t('market.stockTus'), type: 'text3', prop: 'fulls', width: '80' }
      ],
      fbillno: '',
      tableHeader1: [
        { label: this.$t('market.jcfprice'), prop: 'fprocesscost' },
        { label: this.$t('market.note'), prop: 'fremark' },
        { label: this.$t('market.order'), prop: 'fsaleorderno' },
        { label: this.$t('market.proOrderSeq'), prop: 'fmoentrySeq' },
        { label: this.$t('market.demandDate'), prop: 'fneeddate' },
        { label: this.$t('market.stdqty'), prop: 'fstdqty' },
        { label: this.$t('market.unreceQty'), prop: 'fnopickedqty' },
        { label: this.$t('market.fusedqty'), prop: 'fusedqty' }
      ]
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 220px)' : '73vh'
  },
  methods: {
    handleOrder(val) {
      if (val === this.$t('menu.qualityOrder')) {
        this.convert = this.$t('market.scbjy') // '生产订单至品质检验单'
        this.fbillTypeId = 184
        this.orderBool = true
        this.purpoorder1('SX_CHECKOUT')
      } else if (val === this.$t('menu.workFlowOrder')) {
        this.convert = this.$t('market.sczlc')
        this.fbillTypeId = 245
        this.orderBool = true
        this.purpoorder1('SX_PROCESS')
      } else if (val === this.$t('menu.outProcessOrder')) {
        this.convert = this.$t('market.sczgx') // '生产订单至外包工序单'
        this.fbillTypeId = 1317
        this.orderBool = true
        this.purpoorder1('SX_OUTSOURCE')
      } else if (val === this.$t('menu.semifinishDetail')) {
        this.convert = this.$t('market.scylzbcp') // '生产用料单至半成品入库'
        this.fbillTypeId = 1511
        this.orderBool = true
        this.purpoorder1('SX_MOPARTS')
      } else {
        this.orderBool = false
      }
    },
    // 生产流程单
    async purpoorder1(ev) {
      const { data: RES } = await queryViewItem({ viewName: ev })
      this.billTypeData = RES.list
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(item => {
            return (toMxAmina(item), Forbiders(item))
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '生产用料单列表')
        } else {
          querycdList({
            pageSize: 5000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(item => {
                return (toMxAmina(item), Forbiders(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '生产用料单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    load() {
      this.currentPage += 1
      this.handleGetUntreated()
    },
    // 获取生产列表数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        list: this.list,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await querycdList(DATA)
      if (RES.code === 0) {
        this.loading = false
        // this.tableData = this.tableData.concat(RES.data.array)
        this.tableData = RES.data.array
        this.tableData.map(item => {
          return toMxAmina(item)
        })
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 全选
    handleSelectAll(val) {
      this.val = val
      this.fbillno = val[0].fbillNo
      this.selectVal = []
      this.fentryData = []
      this.fidsData = []
      this.fmoData = []
      this.fmoentryData = []
      val.forEach(res => {
        res.fbillNo && this.selectVal.push(res.fbillNo)
        this.fentryData.push(res.fentryId)
        this.fidsData.push(res.fid)
        this.fmoData.push(res.fmoId)
        this.fmoentryData.push(res.fmoentryId)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
      this.fmoData = Array.from(new Set(this.fmoData))
      this.fmoentryData = Array.from(new Set(this.fmoentryData))
    },
    // 下推
    pushDown() {
      if (!this.val) {
        this.$message.error('请选择数据!')
        return
      } else {
        this.isdanjuDialog = true
      }
    },
    pushDownOrder() {
      if (this.orderLX === this.$t('menu.proPickLian')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToPickmtrl(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/productionOrder/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proSupplTong')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToPrdReturnmtrl(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/proSuppleDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proStirageOrder')) {
        const DATA = {
          SoucrceIds: this.fmoData,
          EntryIds: this.fmoentryData
        }
        pushToPrdInstock(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/proStirageOrder/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proTuiStockDetail')) {
        const DATA = {
          SoucrceIds: this.fmoData,
          EntryIds: this.fmoentryData
        }
        pushToPrdUninstock(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/proTuiStockDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.supplementary')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToSupplement(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/supplementaryDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.workFlowOrder')) {
        const DATA = {
          SoucrceIds: this.fmoData,
          EntryIds: this.fmoentryData,
          fbillTypeId: this.fbillTypeId
        }
        insertProcess(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/workFlowDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.qualityOrder')) { // 品质
        const DATA = {
          SoucrceIds: this.fmoData,
          EntryIds: this.fmoentryData,
          fbillTypeId: this.fbillTypeId
        }
        pushMoCheck(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/qualityDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.outProcessOrder')) { // 外包
        const DATA = {
          SoucrceIds: this.fmoData,
          EntryIds: this.fmoentryData,
          fbillTypeId: this.fbillTypeId
        }
        insertOutsource(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/outProcessDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.semifinishDetail')) { // 生产用料单至半成品入库
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData,
          fbillTypeId: this.fbillTypeId
        }
        insertMoparts(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/semifinishDetail/${res.data}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      }
    },
    // 套打
    printing1() {
      const id = this.selectVal.join(',')
      this.$router.push({
        path: `/proIngredient1/${id}`
      })
    },
    // 修改详情
    proUpload(ev) {
      const id = ev.fbillNo
      this.$router.push({ path: `/productionEdit/${id}` })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = {
        Numbers: this.selectVal,
        fIds: this.fidsData,
        EntryIds: this.fentryData
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审批通过
    async audit(ev) {
      if (this.selectVal.length === 0) {
        this.$message({ showClose: true, message: '请选择数据', type: 'warning' })
        return
      }
      const api = ev === 1 ? auditPrdPpboms : unauditPrdPpboms
      this.toExamineFun(api)
    },
    // 提交、反提交
    async submit(ev) {
      const api = ev === 1 ? submitPrdPpboms : unsubmitPrdPpboms
      this.toExamineFun(api)
    },
    settle() {
      const api = finishPrdPpboms
      this.toExamineFun(api)
    },
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.ingredient {
  @include listBom;
  .el-tag {
    height: 20px;
    line-height: 20px;
  }
  .table-content {
    position: relative;
  }
  .header {
    position: relative;
    .header-name {
      width: 100%;
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
